package com.living.filedownloader.ui.adapter;

import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadSampleListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.filedownloader.util.FileDownloadUtils;
import com.living.R;
import com.living.filedownloader.GlobalTasksManager;
import com.living.filedownloader.TasksManager;
import com.living.filedownloader.bean.TasksManagerModel;
import com.md.basedpc.log.Log;

import org.jetbrains.annotations.NotNull;

import java.io.File;

/***
 * 下载适配器
 */
public class TaskItemDownloadingAdapter extends BaseQuickAdapter<TasksManagerModel, TaskItemViewHolder> {


    /**
     * 下载监听
     */
    private FileDownloadListener taskDownloadListener = new FileDownloadSampleListener() {
        private TaskItemViewHolder checkCurrentHolder(final BaseDownloadTask task) {
            final TaskItemViewHolder tag = (TaskItemViewHolder) task.getTag();
            if (tag.taskid != task.getId()) {
                return null;
            }
            return tag;
        }

        @Override
        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.pending(task, soFarBytes, totalBytes);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateDownloading(FileDownloadStatus.pending, soFarBytes, totalBytes);
        }

        @Override
        protected void started(BaseDownloadTask task) {
            super.started(task);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
        }

        @Override
        protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            super.connected(task, etag, isContinue, soFarBytes, totalBytes);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateDownloading(FileDownloadStatus.connected, soFarBytes, totalBytes);
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.progress(task, soFarBytes, totalBytes);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateDownloading(FileDownloadStatus.progress, soFarBytes, totalBytes);
        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            super.error(task, e);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateNotDownloaded(FileDownloadStatus.error, task.getLargeFileSoFarBytes(), task.getLargeFileTotalBytes());
            GlobalTasksManager.getInstance().removeTaskForViewHolder(task.getId());
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            super.paused(task, soFarBytes, totalBytes);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);
            GlobalTasksManager.getInstance().removeTaskForViewHolder(task.getId());
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            super.completed(task);
            final TaskItemViewHolder tag = checkCurrentHolder(task);
            if (tag == null) {
                return;
            }
            tag.updateDownloaded();
            GlobalTasksManager.getInstance().removeTaskForViewHolder(task.getId());
        }
    };

    public TaskItemDownloadingAdapter() {
        super(R.layout.item_downloading_task);
        addChildClickViewIds(R.id.task_action_more);
    }

    @NotNull
    @Override
    protected TaskItemViewHolder onCreateDefViewHolder(@NotNull ViewGroup parent, int viewType) {
        TaskItemViewHolder holder = super.onCreateDefViewHolder(parent, viewType);
        holder.root_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getTag() == null) {
                    return;
                }
                TaskItemViewHolder holder = (TaskItemViewHolder) v.getTag();
                if (holder.downloadStatus == FileDownloadStatus.progress || holder.downloadStatus == FileDownloadStatus.pending) {
                    // to pause
                    FileDownloader.getImpl().pause(holder.taskid);
                } else if (holder.downloadStatus != FileDownloadStatus.completed) {
                    // to start
//                    final TasksManagerModel model = DownLoadManger.getInstance().get(holder.getLayoutPosition());
                    final TasksManagerModel model = getData().get(holder.getLayoutPosition());
                    final BaseDownloadTask task = FileDownloader.getImpl()
                            .create(model.getUrl())
                            .setPath(model.getPath())
                            .setCallbackProgressTimes(TaskItemViewHolder.callbackProgressTimes).setListener(taskDownloadListener);
                    GlobalTasksManager.getInstance().addTaskForViewHolder(task);
                    GlobalTasksManager.getInstance().updateViewHolder(holder.taskid, holder);
                    task.start();
                    Log.e("task id:" + task.getId() + " holder.taskid: " + holder.taskid);
                } else if (holder.downloadStatus == FileDownloadStatus.completed) {
                    // to delete
//                    new File(DownLoadManger.getInstance().get(holder.getLayoutPosition()).getPath()).delete();
//                    holder.updateNotDownloaded(FileDownloadStatus.INVALID_STATUS, 0, 0);

//                    String urlPath = DownLoadManger.getInstance().get(holder.getLayoutPosition()).getPath();
//                    Context context = getContext();
//                    context.startActivity(VideoActivity.newIntent(context, urlPath, "测试播放"));
                }

            }
        });
        return holder;
    }

    @Override
    protected void convert(@NotNull TaskItemViewHolder holder, TasksManagerModel model) {
        holder.update(model.getTaskid());
        holder.root_download.setTag(holder);
        /**
         * 绑定进度 监听
         */
        BaseDownloadTask baseDownloadTask = GlobalTasksManager.getInstance().getTask(model.getTaskid());
        if (baseDownloadTask == null) {
            baseDownloadTask = FileDownloader.getImpl().create(model.getUrl()).setPath(model.getPath()).setCallbackProgressTimes(TaskItemViewHolder.callbackProgressTimes).setListener(taskDownloadListener);
            GlobalTasksManager.getInstance().addTaskForViewHolder(baseDownloadTask);
        }
        GlobalTasksManager.getInstance().updateViewHolder(holder.taskid, holder);
        baseDownloadTask.setListener(taskDownloadListener);

        holder.taskNameTv.setText(model.getAudioId() + "  " + model.getName() + "");
        GlobalTasksManager.getInstance().updateViewHolder(holder.taskid, holder);
        if (TasksManager.getImpl().isReady()) {
            final int status = TasksManager.getImpl().getStatus(model.getTaskid(), model.getPath());
            if (status == FileDownloadStatus.pending || status == FileDownloadStatus.started || status == FileDownloadStatus.connected) {
                // start task, but file not created yet
                holder.updateDownloading(status, TasksManager.getImpl().getSoFar(model.getTaskid()), TasksManager.getImpl().getTotal(model.getTaskid()));
            } else if (!new File(model.getPath()).exists() && !new File(FileDownloadUtils.getTempPath(model.getPath())).exists()) {
                // not exist file
                holder.updateNotDownloaded(status, 0, 0);
            } else if (TasksManager.getImpl().isDownloaded(status)) {
                // already downloaded and exist
                holder.updateDownloaded();
            } else if (status == FileDownloadStatus.progress) {
                // downloading
                holder.updateDownloading(status, TasksManager.getImpl().getSoFar(model.getTaskid()), TasksManager.getImpl().getTotal(model.getTaskid()));
            } else {
                // not start
                holder.updateNotDownloaded(status, TasksManager.getImpl().getSoFar(model.getTaskid()), TasksManager.getImpl().getTotal(model.getTaskid()));
            }
        } else {
            holder.taskStatusTv.setText("点击继续下载");
        }
    }


}
